package org.example.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import eu.bitwalker.useragentutils.UserAgent;
import org.example.system.entity.DealLog;
import org.example.system.mapper.DealLogMapper;
import org.example.system.service.DealLogService;
import org.example.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Date;

/**
 * 交易记录服务层实现类
 */
@Service
public class DealLogServiceImpl implements DealLogService {

    @Autowired
    private DealLogMapper dealLogMapper;

    /**
     * 添加交易记录
     * @param dealLog
     * @param request
     * @return
     */
    @Override
    public int add(DealLog dealLog,HttpServletRequest request) {
        dealLog.setId(null);
        dealLog.setIpAddress(IpUtil.getIpAddr(request));
        try {
            dealLog.setAddress(IpUtil.getIpPossession(IpUtil.getIpAddr(request)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("user-agent"));
        dealLog.setBrowser(userAgent.getBrowser().toString());
        dealLog.setPlatform(userAgent.getOperatingSystem().getName());
        dealLog.setLogTime(new Date());
        return dealLogMapper.insert(dealLog);
    }

    /**
     * 按条件分页查询
     * @param dealLog
     * @return
     */
    @Override
    public IPage<DealLog> selectPage(DealLog dealLog){
        LambdaQueryWrapper<DealLog> wrapper = new LambdaQueryWrapper<>();
        //条件
        if (StrUtil.isNotEmpty(dealLog.getIpAddress())){
            wrapper.like(DealLog:: getIpAddress,dealLog.getIpAddress());    //相似的IP地址（模糊查询）
        }
        if (StrUtil.isNotEmpty(dealLog.getUsername())){
            wrapper.like(DealLog:: getUsername,dealLog.getUsername());    //相似的用户名（模糊查询）
        }
        if (StrUtil.isNotEmpty(dealLog.getBlock())){
            wrapper.eq(DealLog:: getBlock,dealLog.getBlock());    //相同的功能模块（精确查询）
        }
        wrapper.orderByDesc(DealLog::getLogTime);
        IPage<DealLog> page = new Page<>();
        page.setCurrent(dealLog.getPageNum());
        page.setSize(dealLog.getPageSize());
        return dealLogMapper.selectPage(page,wrapper);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @Override
    public int deleteBatch(Long[] ids) {
        return dealLogMapper.deleteBatchIds(Arrays.asList(ids));
    }
}
